﻿using BLL;
using Mode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LibraryMIS2019
{
    public partial class LibraryUI : Form
    {
        private string operation = "I";//图书操作类型变量，当为I时是新增书籍，当为U时是更新书籍信息
        BusinessLogic logic = new BusinessLogic();
        DataSet ds; //定义数据集对象

        bool State = false;//
        public LibraryUI()
        {
            InitializeComponent();
        }

        private void toolStripContainer1_TopToolStripPanel_Click(object sender, EventArgs e)
        {

        }
        #region 图书类别下拉菜单实现
        private void DropDownBookClass(ComboBox  controlName)
        {          
            DataSet bookClass = logic.GetBookClass();
            //数据源绑定到控件
            controlName.DataSource = bookClass.Tables[0];
            controlName.DisplayMember = "className";
            controlName.ValueMember = "classId";
        }
        private void tushuleibie1_VisibleChanged(object sender, EventArgs e)
        {
            try
            {
                DropDownBookClass(tushuleibie1);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "系统信息");
            }
        }

        private void tushulebie2_VisibleChanged(object sender, EventArgs e)
        {
            try
            {
                DropDownBookClass(tushulebie2);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统信息");
            }
        }
        #endregion 图书信息处理
        /// <summary>
        /// 书籍入库数据效验
        /// </summary>
        /// <returns></returns>
        private string BookInfoDataValidatuon()
        {
            if (textBox1bookid.Text == "")
            {
                textBox1bookid.Focus();
                return "索书号不能为空！";
            }
            if (textBox2ISBN.Text == "")
            {
                textBox2ISBN.Focus();
                return "ISBN不能为空！";
            }
            if (textBox6author.Text == "")
            {
                textBox6author.Focus();
                return "作者不能为空！";
            }
            if (textBox5bookname1.Text == "")
            {
                textBox5bookname1.Focus();
                return "书名不能为空！";
            }
            if (chubanshe.Text == "")
            {
                chubanshe.Focus();
                return "出版社不能为空！";
            }
            return "";
        }
        private Bookclass FindBookClassByBookClassID(string bookClassID)
        {
            return logic.FindBookClass(bookClassID);
        }
        /// <summary>
        /// 图书新增、更新操作单选按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void queren_Click(object sender, EventArgs e)
        {
            string errorString = BookInfoDataValidatuon();
            if (errorString .Length >0)
            {            
                MessageBox.Show(errorString, "系统提示");return;
            }
            //获取控件
            Bookinfo bo = new Bookinfo();
            bo.bookID = textBox1bookid.Text.Trim();
            bo.bookName  = textBox5bookname1.Text.Trim();
            bo.author  = textBox6author.Text.Trim();
            bo.ISBN  = textBox2ISBN.Text.Trim();
            bo.publisher  = chubanshe .Text.Trim();
            //日期控件取值处理
            bo.publishDate = chubanriqi.Value.Date;
            if (textBox3zishu.Text =="")
            {
                bo.wordCount = 0;
            ;
            }
            else
            {
                bo.wordCount = Convert.ToInt32(textBox3zishu.Text.Trim())
            ;
            }
            if (textBox7yeshu.Text == "")
            {
                bo.pageCount  = 0;
            }
            else
            {
                bo.pageCount   = Convert.ToInt32(textBox7yeshu.Text.Trim())
            ;
            }
            if (textBox4banben.Text == "")
            {
                bo.bookVersion = textBox4banben.Text.Trim();
            }
            else
            {
                bo.bookVersion = "";
            }
            //获取下拉菜单控件的值
            var bookClassID = tushuleibie1.SelectedValue.ToString().Trim();
            //根据图书类别编号获取对应图书类别记录
            Bookclass po = FindBookClassByBookClassID(bookClassID);
            bo.Bookclass  = po;


            logic = new BusinessLogic();
            object obj = logic.EditBook(bo, operation);
            if (obj != null)
            {
                if (obj.ToString() == "这是重复记录")
                    MessageBox.Show("重复数据，请勿重复插入！", "系统提示");
                else
                    MessageBox.Show("操作成功，数据已成功刷新", "系统提示");
            }
            quxiao_Click(null, null);//调用撤销单击事件进行控件清空处理
        }
        /// <summary>
        /// 选择“新书入库”单选按钮
        /// </summary>
        private void newbook_CheckedChanged(object sender, EventArgs e)
        {
            operation = "I";
        }
        /// <summary>
        /// 选择“更新数据信息”单选按钮
        /// </summary>
        private void Updatebooks_CheckedChanged(object sender, EventArgs e)
        {
            operation = "U";
        }
        /// <summary>
        /// 图书搜索功能实现
        /// </summary>
        private void chaxun_Click(object sender, EventArgs e)
        {
            string bookname = tushuming.Text.Trim();//获取用户输入的书名查找关键字
            string classname = tushulebie2.Text.Trim();
            ds = logic.GetBookByBookNameOrClassname(bookname, classname);//根据书名、类别名查找图书信息
            if (ds != null)
            {
                dataGridView1.DataSource = ds.Tables[0];

            }
            else
                MessageBox.Show("没有查询到结果", "系统提示");
        }
        /// <summary>
        /// 单元格单击事件
        /// </summary>
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            var selectBookId = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();//获取被选行的索书号值
            ds = logic.GetBookByBookId(selectBookId);
            if (ds.Tables[0].Rows.Count > 0)
            {
                textBox1bookid.Text = ds.Tables[0].Rows[0][0].ToString();
                textBox2ISBN.Text = ds.Tables[0].Rows[0][1].ToString();
                textBox5bookname1.Text = ds.Tables[0].Rows[0][2].ToString();
                textBox6author.Text = ds.Tables[0].Rows[0][3].ToString();
                chubanriqi.Text = ds.Tables[0].Rows[0][4].ToString();
                textBox4banben.Text = ds.Tables[0].Rows[0][5].ToString();
                textBox3zishu.Text = ds.Tables[0].Rows[0][6].ToString();
                textBox7yeshu.Text = ds.Tables[0].Rows[0][7].ToString();
                chubanshe.Text = ds.Tables[0].Rows[0][8].ToString();
                tushuleibie1.Text = ds.Tables[0].Rows[0][10].ToString();
            }
        }
        /// <summary>        /// 撤销按钮        /// </summary>
        private void quxiao_Click(object sender, EventArgs e)
        {
            ClearControl(newbook);
            newbook.Checked = true;
            var today = DateTime.Now;
            chubanriqi.Value = today;
        }
        private void ClearControl(Control controlName)
        {
            for (int index = 0; index < controlName.Controls.Count; index++)
            {
                // 如果是容器内部控件，则递归调用自己
                if (controlName.Controls[index].HasChildren)
                {
                    ClearControl(controlName.Controls[index]);
                }
                else
                {
                    switch (controlName.Controls[index].GetType().Name)
                    {
                        case "TextBox":
                            (controlName.Controls[index] as TextBox).Text = "";
                            break;
                        case "RadioButton":
                            (controlName.Controls[index] as RadioButton).Checked = false;
                            break;
                        case "CheckBox":
                            (controlName.Controls[index] as CheckBox).Checked = false;
                            break;
                        case "ComboBox":
                            (controlName.Controls[index] as ComboBox).Text = "";
                            (controlName.Controls[index] as ComboBox).SelectedIndex = -1;
                            break;
                        case "DataGridView":
                            (controlName.Controls[index] as DataGridView).DataSource = null;
                            break;
                        case "ListBox":
                            (controlName.Controls[index] as ListBox).Items.Clear();
                            break;
                        case "DateTimePicker":
                            (controlName.Controls[index] as DateTimePicker).Checked = false;
                            break;
                    }
                }
            }
        }
        /// <summary>        /// 删除记录        /// </summary>
        private void sanchu_Click(object sender, EventArgs e)
        {
            MessageBoxButtons systemBtn = MessageBoxButtons.OKCancel;//定义确定取消消息按钮
            DialogResult result = MessageBox.Show("你确定删除该数据吗？", "系统提示", systemBtn);//定义系统提示并将其赋值给对话框对象
            if (result == DialogResult.OK)
            {
                string bookid = textBox1bookid.Text.Trim();//获取索书号
                if (logic.DeleteBook(bookid))
                {
                    MessageBox.Show("已成功删除该条记录！", "系统信息");
                    //刷新DataGridView数据源信息
                }
                else
                    MessageBox.Show("记录删除失败！请查证后再操作。", "系统信息");
                string bookname = tushuming.Text.Trim();//获取用户输入的书名查找关键字
                string classname = tushulebie2.Text.Trim();
                ds = logic.GetBookByBookNameOrClassname(bookname, classname);
                if (ds != null)
                    dataGridView1.DataSource = ds.Tables[0];
            }
            else return;
        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }

        private void groupBox4_Enter(object sender, EventArgs e)
        {

        }

        private void 用户管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 4;
        }

        private void 信息维护ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 5;
        }

        private void 图书管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 0;
        }

        private void 借书管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 1;
        }

        private void 还书管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 2;
        }

        private void 续借管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 3;
        }

        private void 表报ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 6;
        }

        private void 提出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);//这是最彻底的退出方式，
        }

        private void 关于我们ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("软件技术2班荣誉出品", "系统提示");
        }


        /// <summary>
        /// 图书借阅模块
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>


        private void Showtag2pbPhoto(string userid)
        {
            if (logic.GetPhotoByUserID(userid) != null)
                Photo.Image = Image.FromStream(logic.GetPhotoByUserID(userid));
        }
        private void button1queding_Click(object sender, EventArgs e)
        {
            if (textBox1duzhehao.Text.Trim() != "")
            {
                string userid = textBox1duzhehao.Text.Trim();
                logic = new BusinessLogic();
                DataSet Userlist = logic.GetUserInfo(userid);//根据用户id获取用户信息

                //判断查询集userlist的空值情况
                if (Userlist.Tables.Count == 1 && Userlist.Tables[0].Rows.Count == 0)
                {
                    MessageBox.Show("没有此用户信息请重新输入", "系统提示");
                    textBox1duzhehao.Clear();
                    textBox1duzhehao.Focus();
                }
                else
                {
                    textBox1xingming.Text = Userlist.Tables[0].Rows[0][3].ToString();
                    textBox2classname.Text = Userlist.Tables[0].Rows[0][7].ToString();
                    string gender = Userlist.Tables[0].Rows[0][4].ToString();
                    if (gender == "True")
                        male.Checked = true;
                    else
                        female.Checked = true;
                    Showtag2pbPhoto(userid);
                    //
                    ds = logic.GetBorrowBookByUserID(userid);
                    if (ds.Tables[0].Rows.Count != 0)
                    {
                        dataGridView2.DataSource = ds.Tables[0];
                    }
                    else
                    {
                        MessageBox.Show("该读者没有未归还记录", "系统提示");
                    }
                }
            }
            else
            {
                MessageBox.Show("请输入读者号", "系统提示");
                textBox1duzhehao.Focus();
            }
        }

        private void button3jiechu_Click(object sender, EventArgs e)
        {
            string bookid = textBox2suoshuhao.Text.Trim();//获取索书号
            string userid= textBox1duzhehao.Text.Trim();//获取读者号
            DateTime nowTime = DateTime.Now;//获取当前时间作为借出日期

            object ob;
            logic = new BusinessLogic();
            ob = logic.InsertBorrowInfo(bookid, userid);
            if (ob.ToString() == "不可借")
                MessageBox.Show("该书已被借出，不能再借！", "系统提示");
            else if (ob.ToString() == "true")
                MessageBox.Show("借书成功！", "系统提示");
            else
                MessageBox.Show("借书失败！", "系统提示");
        }



        /// <summary>
        /// 还书管理模块
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonCHaxun_Click(object sender, EventArgs e)
        {
            string bookid = buttonCHaxun.Text.Trim();//获取索书号1000
            if (bookid .Length ==0)
            {
                MessageBox.Show("索书号不能为空", "系统提示");
                buttonCHaxun.Focus();
                return;
            }
            if (!State )
            {
                try
                {
                    ds = logic.GetBorrowInfo("", bookid);
                    if (ds.Tables [0].Rows .Count >0)
                    {
                        textISBn.Text = ds.Tables[0].Rows[0][7].ToString();
                        textBoxbookname.Text = ds.Tables[0].Rows[0][8].ToString();
                        textBoxchubanshe.Text = ds.Tables[0].Rows[0][14].ToString();
                        textBoxzuozhe.Text = ds.Tables[0].Rows[0][9].ToString();
                        textBoxxingming.Text = ds.Tables[0].Rows[0][2].ToString();
                        textBoxClass.Text = ds.Tables[0].Rows[0][3].ToString();

                        //男。女单选按钮被选状态实现
                        string gender = ds.Tables[0].Rows[0][4].ToString();
                        if (gender == "女")
                            radioNU.Checked  = true;
                        else
                            radioNan.Checked  = false;

                        //是否逾期处理
                        var borrowDate= ds.Tables[0].Rows[0][5].ToString();//获取借出日期
                        DateTime BorrowDate = Convert.ToDateTime(borrowDate);//借出日期转型成为日期类型
                        if ((DateTime.Now - BorrowDate).Days > 30)
                            radioSHI.Checked = true;//逾期
                        else
                            radioFOU.Checked = false;//不逾期


                        //用户借阅信息处理
                        string userid = ds.Tables[0].Rows[0][0].ToString();//获取用户读者编号
                        DataSet borrowInfoByUser = logic.GetBorrowInfo(userid, "");//根据用户编号获取借阅信息
                        if (borrowInfoByUser.Tables[0].Rows.Count > 0)
                        {
                            dataGridBorrow.DataSource = borrowInfoByUser.Tables[0];
                            buttonCHaxun.Text = "还书";//将查询按钮修改为还书按钮
                            State = true;//将状态阀值修改，true:还书操作
                        }
                        else
                            MessageBox.Show("该用户没有任何借阅记录！", "系统提示");
                    }
                }
                catch (Exception ex)
                {
                    throw (ex);
                }
            }
            else
            {
                if (State )
                {
                    if (logic.ReturnBook(bookid))
                    {
                        MessageBox.Show("还书成功", "系统提示");
                        State = false;
                    }
                    else
                        MessageBox.Show("还书失败", "系统提示");
                }
            }
        }
        #region  
        private void buttonquXiao_Click(object sender, EventArgs e)
        {

        }

        private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {

        }

        private void label17_Click(object sender, EventArgs e)
        {

        }
        #endregion

        /// <summary>
        /// 续借管理模块
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tag4btnSearch_Click(object sender, EventArgs e)
        {
            string bookid = tag4txtbooid.Text.Trim();
            if (bookid.Length == 0)
            {
                MessageBox.Show("索书号不能为空，请进行输入！", "系统提示");
                tag4txtbooid.Focus();
                return;
            }
            if (!State)
            {
                try
                {
                    ds = logic.GetBorrowInfo("", bookid);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        tag4txtISBN.Text = ds.Tables[0].Rows[0][7].ToString();
                        tag4txtBookName.Text = ds.Tables[0].Rows[0][8].ToString();
                        tag4txtPublisher.Text = ds.Tables[0].Rows[0][14].ToString();
                        tag4txtAuthor.Text = ds.Tables[0].Rows[0][9].ToString();
                        tag4txtUserName.Text = ds.Tables[0].Rows[0][2].ToString();
                        tag4txtClassName1.Text = ds.Tables[0].Rows[0][3].ToString();
                        string gender = ds.Tables[0].Rows[0][4].ToString();
                        if (gender == "女")
                            tag4rbFemale.Checked = true;
                        else
                            tag4rbMale.Checked = false;
                        var borrowDate = ds.Tables[0].Rows[0][5].ToString();//获取借出日期
                        DateTime BorrowDate = Convert.ToDateTime(borrowDate);//借出日期转型成为日期类型
                        if ((DateTime.Now - BorrowDate).Days > 30)
                            tag4rbOverdueYes.Checked = true;//逾期
                        else
                            tag4rbOverdueNo.Checked = false;//不逾期

                        //用户借阅信息处理
                        string userid = ds.Tables[0].Rows[0][0].ToString();//获取用户读者编号
                        DataSet borrowInfoByUser = logic.GetBorrowInfo(userid, "");//根据用户编号获取借阅信息
                        if (borrowInfoByUser.Tables[0].Rows.Count > 0)
                        {
                            tag4dgBorrowInfo.DataSource = borrowInfoByUser.Tables[0];
                            tag4btnSearch.Text = "续借";//将查询按钮修改为还书按钮
                            State = true;//将状态阀值修改，true:还书操作
                        }
                        else
                            MessageBox.Show("该用户没有任何借阅记录！", "系统提示");
                    }
                }
                catch (Exception ex)
                {
                    throw (ex);
                }
            }
            else
            {
                if (State)
                {
                    if (logic.RenewBook (bookid))
                    {
                        MessageBox.Show("续借成功", "系统提示");
                        State = false;
                    }
                    else
                        MessageBox.Show("续借失败", "系统提示");
                }
            }
        }

        /// <summary>
        /// 读者管理模块
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private string userinfoDataValidation()
        {
            if (tag5txtReaderID.Text == "") { tag5txtReaderID.Focus(); return "读者号不能为空值！"; }
            if (tag5txtReaderName.Text == "") { tag5txtReaderName.Focus(); return "姓名不能为空值！"; }
            if (tag5txtPwd.Text == "") { tag5txtPwd.Focus(); return "密码不能为空值！"; }
           
            return "";
        }
        private Classinfo   FindUserInfoByUserClassID(int  ClassName)
        {
            return logic.FindClassInfo(ClassName);
        }
        private void tag5btnOK_Click(object sender, EventArgs e)
        {
            string errorString = userinfoDataValidation();
            if (errorString.Length > 0) { MessageBox.Show(errorString, "系统提示"); return; }
            userinfo bo = new userinfo();
            bo.userId  = tag5txtReaderID.Text.Trim();
            bo.userName   = tag5txtReaderName.Text.Trim();
            bo.pwd  = tag5txtPwd.Text.Trim();          
            bo.email  = tag5txtEmail.Text.Trim();
            
            int  ClassName= Convert .ToInt32  (comboClassname.SelectedValue.ToString().Trim());

           
            //根据图书类别编号获取对应图书类别记录
           FindUserInfoByUserClassID(ClassName );
            bo.className    = ClassName;

            logic = new BusinessLogic();
            object obj = logic.EditClass(bo, operation);
            if (obj != null)
            {
                if (obj.ToString() == "这是重复记录")
                    MessageBox.Show("重复数据，请勿重复插入！", "系统提示");
                else
                    MessageBox.Show("操作成功，数据已成功刷新", "系统提示");
            }
            tag5btnCancel1_Click(null, null);//调用撤销单击事件进行控件清空处理
        }
        /// <summary>
        /// 
        /// </summary>
        private void DropDownUserClass(ComboBox controlName)
        {
            DataSet ClassInfo = logic.GetClassInfo();
            //数据源绑定到控件
            controlName.DataSource = ClassInfo.Tables[0];
            controlName.DisplayMember = "className";
            controlName.ValueMember = "classId";
        }

        private void comboClassname_VisibleChanged(object sender, EventArgs e)
        {
            try
            {
                DropDownUserClass(comboClassname);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统信息");
            }
        }

        private void tag5cboxClassName_VisibleChanged(object sender, EventArgs e)
        {
            try
            {
                DropDownUserClass(tag5cboxClassName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统信息");
            }
        }

        private void tag5btnCancel1_Click(object sender, EventArgs e)
        {

        }

        private void tag5rbInsert_CheckedChanged(object sender, EventArgs e)
        {
            operation = "I";
        }

        private void tag5rbUpdate_CheckedChanged(object sender, EventArgs e)
        {
            operation = "U";
        }

        private void tag5rbMale_CheckedChanged(object sender, EventArgs e)
        {
            userinfo bo = new userinfo();
            bo.gender = true;
        }

        private void tag5rbFemale_CheckedChanged(object sender, EventArgs e)
        {
            userinfo bo = new userinfo();
            bo.gender = false ;
        }

        private void tag5btnSearch_Click(object sender, EventArgs e)
        {
            string UserId = tag5txtReaderCode.Text.Trim();//获取用户输入的书名查找关键字
            string classname = tag5cboxClassName.Text.Trim();
            ds = logic.GetUserByUserIdOrClassname(UserId, classname);//根据书名、类别名查找图书信息
            if (ds != null)
            {
                tag5dgvReader.DataSource = ds.Tables[0];

            }
            else
                MessageBox.Show("没有查询到结果", "系统提示");
        }
    }
}
